<?php
class SystemAction extends BaseAction {

	public function _initialize() {
		parent::_initialize();
		$xdata	=	model('Xdata');
		$opt	=	$xdata->lget('site');
		$this->assign("opt",$opt);
	}

    /*
     * 站点设置
     *
     */
	public function index() {
		require_cache(SITE_PATH.'/addons/libs/Think/Dir.class.php');
		$pDir = new Dir(SITE_PATH.'/public/themes/');
		$this->assign('themelist',$pDir->toArray());
		$this->display();
	}

    /*
     * 保存站点设置
     *
     */
	function doSaveSiteOption() {
		$xdata	=	model('Xdata');
		$result	=	$xdata->lput('site',$_POST);
		if($result){
			$this->success('站点设置保存成功！');
		}else{
			$this->error('站点设置保存失败！');
		}
	}

    /*
     * 隐私设置
     *
     */
    function privacy() {
		$opt = D("Option")->getOpts4Edit();
		$this->assign("allow_ips",$opt["allow_ips"]);
		$this->assign("deny_ips",$opt["deny_ips"]);
		$this->assign("privacy",unserialize($opt["privacy"]));


		$this->display();
   }

    /*
     * 审核设置
     *
     */
	function auditing() {
		$opt = D("Option")->getOpts4Edit();

		$this->assign("gfw_enable",$opt["gfw_enable"]);
		$this->assign("gfw_keywords",$opt["gfw_keywords"]);
		$this->assign("gfw_rep",$opt["gfw_rep"]);

		$this->display();
	}



    /*
     *  保存审核设置
     *
     */
	function doAuditing() {
		//存到库里
		$dao = D("Option");
		foreach($_POST as $k=>$v) {
				$dao->setField("value",$v,"name='".$k."' AND appname='thinksns'");
		}
		//更新缓存
		$opt = D("Option")->updateCache();
		$this->redirect("auditing");
	}


    /*
     * 公告设置
     *
     */
	function gonggao() {
		$opt = D("Option")->getOpts4Edit();
		$this->assign("gonggao",$opt["gonggao"]);
		$this->assign("gonggao_open",$opt["gonggao_open"]);
		$this->assign('smileList',$this->getSmile($this->opts['ico_type']));
		$this->assign('smilePath',$this->getSmilePath($this->opts['ico_type']));
		$this->display();
	}


    /*
     * 设置公共
     *
     */
        function doGonggao() {
        //存到库里
                set_magic_quotes_runtime(0);
                //		dump($_POST);
                //		 dump(stripslashes($_POST["content"]));
                //		 return;
                //
                $dao = D("Option");

                $dao->setField("value",stripslashes($_POST["gg_content"]),"name='gonggao' AND appname='thinksns'");
                $dao->setField("value",stripslashes($_POST["gonggao_open"]),"name='gonggao_open' AND appname='thinksns'");

                //更新缓存
                $opt = D("Option")->updateCache();


                $this->redirect("/System/gonggao/t/1");
        }




    /*
     * 添加广告页
     *
     */
        public function ad_add() {

                if($id = $_GET["id"]) {

                        $ad = D("Ad")->find($id);
                        $this->assign("ad",$ad);

                }else {
                        $ads = D("Ad")->field("place")->findAll();
                        foreach($ads as $k=>$v) {
                                $places[] = $v["place"];
                        }
                        $this->assign("places",$places);
                }
                $this->assign('smileList',$this->getSmile($this->opts['ico_type']));
                $this->assign('smilePath',$this->getSmilePath($this->opts['ico_type']));
                $this->display();
        }



    /*
     * 添加广告
     *
     */
        function doAddAd() {

                set_magic_quotes_runtime(0);

                $dao = D("Ad");

                $r = $dao->create();
                if(false === $r) $this->error($dao->getError());

                if($dao->id) {
                        $dao->save();
                }else {
                        $id = $dao->add();
                }


                $this->redirect("ad_list");
        }



    /*
     * ad列表
     *
     */
        function ad_list() {
                $dao = D("Ad");

                $data = $dao->where($map)->order("id desc")->findAll();

                $this->assign("ads",$data);


                $this->display();
        }

	/*
	 * 删除广告
	 *
	 */
        public function delAd() {
        // 根据id删除指定的记录
                $dao = D("Ad");
                $id = $_REQUEST["id"];
                $id_arr = explode(",",$id);

                foreach($id_arr as $k=>$v) {
                        if(is_numeric($v)) {
                                $dao->delete($v);
                        }
                }

                $this->redirect("ad_list");
        }



    /*
     * 上传公告里的图片
     *
     */
        function up_edit_img() {
                $attachdir = "./data/tip";//上传文件保存路径，结尾不要带/
                $state=$this->_uploadfile('upload',$attachdir);
                echo json_encode($state);
        }


    /*
     * 上传AD里的图片
     *
     */
        function up_ad_img() {
                $attachdir = "./data/ad";//上传文件保存路径，结尾不要带/
                $state=$this->_uploadfile('upload',$attachdir);
                echo json_encode($state);
        }


   /*
     * 添加链接
     *
     */
        public function links_add() {

                if($id = $_GET["id"]) {

                        $link = D("Links")->find($id);
                        $this->assign("link",$link);

                }

                $this->display();
        }


    /*
     * 链接列表
     *
     */
        function links_list() {


                $dao = D("Links");

                $links = $dao->where($map)->order("sort asc")->findAll();
                $this->assign("links",$links);

                $this->display();
        }



    /*
     * 增加链接
     *
     */
        function doLinks() {


                $dao = D("Links");

                $r = $dao->create();
                if(false === $r) $this->error($dao->getError());

                if($dao->id) {
                        $dao->save();
                }else {
                        $id = $dao->add();
                }

                $this->redirect("links_list");
        }

    /*
     * 删除links
     *
     */
        function doDelLinks() {
                $ids = $_GET["ids"];

                $ids_arr = explode(",",$ids);
                foreach($ids_arr as $k=>$v) {
                        D("Links")->delete($v);
                }

                $this->redirect("links_list");

        }

    /*
     * 设置link状态
     *
     */
        function doShenLinks() {
                $dao = D("Links");

                $ids = $_GET["ids"];
                $ids_arr = explode(",",$ids);


                foreach($ids_arr as $k=>$v) {
                        $dao->setField("status",$_GET["status"],"id=".$v);
                }

                $this->redirect("links_list");
        }

    /*
     * 设置link顺序
     *
     */
        function doSortLinks() {
                $dao = D("Links");

                $sort = $_POST["sort"];

                foreach($sort as $id=>$s) {
                        $dao->setField("sort",$s,"id=".$id);
                }

                $this->redirect("links_list");
        }


	/*
	 * 举报列表
	 *
	 */
        function report() {

                $dao = D("Report");

                $data = $dao->where($map)->order("cTime desc")->findPage(10);

                foreach ($data['data'] as $key=>$value) {
                        $data['data'][$key]['url'] = $this->api->App_getAppInfo($value['appid'],'APP_URL').$value['url'];
                }

                $this->assign("reprots",$data["data"]);
                $this->assign("page",$data["html"]);

                $this->display();



        //dump($data["data"]);

        //		echo "<table>";
        //		echo "<tr>";
        //		echo "<td>举报人</td>";
        //		echo "<td>链接</td>";
        //        echo "<td>原因</td>";
        //		echo "<td>举报时间</td>";
        //		echo "</tr>";
        //
        //		foreach($data["data"] as $key=>$v){
        //			echo "<tr>";
        //			echo "<td>".getUserName($v["uid"])."</td>";
        //			echo "<td><a href='".$v["url"]."'>".getShort($v["info"],30)."</a></td>";
        //            echo "<td>".$v["reason"]."</td>";
        //			echo "<td>".friendlyDate($v["cTime"])."</td>";
        //			echo "</tr>";
        //		}
        //
        //		echo "</table>";
        }

        function friend() {
                $friendGroup = D( 'FriendGroup' );
                $category = $friendGroup->getCategory();
                $this->assign( 'category_list',$category );
                $this->display();
        }


        public function doDeleteCategory() {
                $id['id']      = array( "in",$_POST['id']);
                $category = D( 'FriendGroup' );
                if( $result = $category->deleteCategory( $id ) ) {
                        if( strpos( $_POST['id'],',' ) === false ) {
                                echo 1;
                        }else {
                                echo 2;
                        }
                }else {
                        echo -1;
                }
        }
        /**
         * doAddCategory
         * 修改分类
         * @access public
         * @return void
         */
        public function doAddCategory() {
                $category = D( 'FriendGroup' );
                if( $result   = $category->addCategory( $_POST ) ) {
                        echo $result ;
                }else {
                        echo -1;
                }
        }

        public function doEditCategory() {
                $category = D( 'FriendGroup' );
                $result   = $category->editCategory( $_POST['name'] );
                $this->redirect('friend');


//                if( $result   = $category->editCategory( $_POST['name'] ) ) {
//                        $this->redirect('friend');
//                }else {
//                        $this->error( "修改失败" );
//                }

        }
        function _uploadfile($inputname,$attachdir) {

                if(!checkDir($attachdir."/")) {
                        return '目录创建失败: '.$attachdir;
                }
                $dirtype=1;//1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
                $maxattachsize=2097152;//最大上传大小，默认是2M

                $err = "";
                $msg = "";
                $upfile=$_FILES[$inputname];
                if(!empty($upfile['error'])) {
                        switch($upfile['error']) {
                                case '1':
                                        $err = '文件大小超过了php.ini定义的upload_max_filesize值';
                                        break;
                                case '2':
                                        $err = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
                                        break;
                                case '3':
                                        $err = '文件上传不完全';
                                        break;
                                case '4':
                                        $err = '无文件上传';
                                        break;
                                case '6':
                                        $err = '缺少临时文件夹';
                                        break;
                                case '7':
                                        $err = '写文件失败';
                                        break;
                                case '8':
                                        $err = '上传被其它扩展中断';
                                        break;
                                case '999':
                                default:
                                        $err = '无有效错误代码';
                        }
                }
                elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none') {
                        $err = '无文件上传';
                }
                else {
                        $temppath=$upfile['tmp_name'];
                        $attachinfo= @getimagesize($temppath);
                        if($attachinfo[2]==IMAGETYPE_GIF||$attachinfo[2]==IMAGETYPE_JPEG||$attachinfo[2]==IMAGETYPE_PNG) {
                                $extension=image_type_to_extension($attachinfo[2],false);
                                $filesize=filesize($temppath);
                                if($filesize <= $maxattachsize) {
                                        switch($dirtype) {
                                                case 1: $attach_subdir = 'day_'.date('ymd'); break;
                                                case 2: $attach_subdir = 'month_'.date('ym'); break;
                                                case 3: $attach_subdir = 'ext_'.$extension; break;
                                        }
                                        $attach_dir = $attachdir.'/'.$attach_subdir;
                                        if(!is_dir($attach_dir)) {
                                                @mkdir($attach_dir, 0777);
                                                @fclose(fopen($attach_dir.'/index.htm', 'w'));
                                        }
                                        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
                                        $filename=date("YmdHis").mt_rand(1000,9999).'.'.$extension;
                                        $target2 = $attach_dir.'/'.$filename;

                                        $attachdir = ltrim($attachdir,".");
                                        $target = C("TS_URL").$attachdir."/".$attach_subdir."/".$filename;

                                        move_uploaded_file($upfile['tmp_name'],$target2);
                                        $msg=$target;
                                }
                                else $err='文件大小超过'.$maxattachsize.'字节';
                        }
                        else $err='文件格式必需为以下格式：jpg,gif,png';

                        @unlink($temppath);
                }
                return array('err'=>$err,'msg'=>$msg);
        }


        function update() {
        //    	$pFeed= D('Feed');
        //    	$map ="type IN ('group_album','group_file','group_photo','group_topic')";
        //    	$grouplist = $pFeed->where($map)->field('appid,id')->findall();
        //    	foreach ($grouplist as $v){
        //    		$t = explode('_',$v['appid']);
        //    		$date['fid'] = $t[1];
        //    		$maps['id'] = $v['id'];
        //
        //    		$pFeed->where($maps)->save($date);
        //    		unset($date);
        //    		unset($maps);
        //    	}
        //    	$feedArr = array(
        //    		'0' => "'app_add','head','info'",
        //    		'4' => "'blog'",
        //    		'14' => "'event'",
        //    		'3' => "'mini'",
        //    		'10' => "'photo'",
        //    		'11' => "'share_album','share_blog','share_event','share_flash','share_group','share_music','share_photo','share_picture','share_topic','share_url','share_user','share_video','share_vote'",
        //   		'12' =>"'group_album','group_file','group_photo','group_topic'",
        //    		'13' =>"'vote_add','vote_in'",
        //    	);
        //
        //    	//更新动态数据
        //    	foreach ($feedArr as $key=>$value){
        //    		$date['appid'] = intval($key);
        //    		$pFeed->where("type in (".$value.")")->save($date);
        //    	}
        //    	echo '动态更新完成<br>';

                $pNotify = D('Notify');
                $notifyArr = array(
                    '0' => "'add_friend','agree_friend','comment_comment'",
                    '11' => "'share_notice','share_comment'",
                    '3' => "'mini_comment'",
                    '12' => "'group','group_reply','group_topic_quote'",
                    '4' => "'blog_mention','blog_comment'",
                    '13' => "'vote_comment','vote_in'",
                    '14' => "'event_comment'",
                    '10' => "'photo_comment'",
                );

                //更新通知数据
                foreach ($notifyArr as $nkey=>$nvalue) {
                        $ndate['appid'] = intval($nkey);
                        $pNotify->where("type in (".$nvalue.")")->save($ndate);
                }
                echo '通知更新完成<br>';

        }


        //
        function updateshare() {
        //动态数据
                $list = D('FeedTemplate')->query("SELECT id,type,body_data FROM `ts_feed` WHERE type like '%share%'");
                $pFeed = D('Feed');
                foreach ($list as $v) {
                        $id = $v['id'];

                        $body = unserialize(stripcslashes($v['body_data']));

                        foreach ($body as $k=>$v1) {
                                $body[$k]  = str_replace('SITE_URL','WR',$v1);
                        }

                        $date['body_data'] = serialize($body);
                        $map['id']  = $v['id'];
                        $pFeed->where($map)->save($date);
                        unset($date);
                        unset($map);
                        dump($res);
                        dump($pFeed->getLastSql());
                }


        //			分享数据
        //
        //			$list = $pFeed->query("SELECT id,url,data FROM ts_share");
        //			foreach ($list as $v){
        //				$data = unserialize($v['data']);
        //
        //				foreach ($data as $k=>$v1){
        //					$d = str_replace('SITE_URL','WR',$v1);
        //					$data[$k] = str_replace('__ROOT__','WR',$d);
        //				}
        //				$data = serialize($data);
        //				$u = str_replace('SITE_URL','WR',$v['url']);
        //				$url = str_replace('__ROOT__','WR',$u);
        //				$id = $v['id'];
        //				$res = $pFeed->query("UPDATE `ts_share` SET url='$url', data='$data'  WHERE id='$id'");
        //	       }
        }

        /**
         * ico
         * 图像设置
         * @access public
         * @return void
         */
        public function ico () {
                $smilDao = D('Smile');
                //获取数据库的表情列表
                $smiletype     =  $smilDao->getSmileType() ;
                $this->assign( 'smiletype' , $smiletype );
                $this->display();
        }


        public function smile() {
                $smilDao = D('Smile');
                if( !isset( $_GET['type'] ) ) {
                        $type = $_POST['type'];
                        //检查合法性
                        if( empty( $type ) )
                                $this->error( "没有填写表情分类" );

                        if( $smilDao->where( "type='{$type}'" )->getField( 'id' ) )
                                $this->error( $type."已经存在" );

                        $smilelist = $smilDao->getSmileFileList( $type );
                        if( !$smilelist )
                                $this->error( $type."不存在表情根目录下" );
                        $smilelist['type'] = $type;
                        $smilDao->addSmile( $smilelist );
                        $smilelist = $smilDao->getSmileList( $type );
                }else {
                        $type      = $_GET['type'];
                        $smilelist = $smilDao->getSmileList($type);
                        if( isset( $_GET['doUpdate'] ) ) {
                                $smilelist1 = $smilDao->getSmileFileList( $type );
                                $smilelist = $smilDao->filterData( $smilelist,$smilelist1,$type );
                        }
                //去处已经添加的
                }

                $path      = __URL__."/doAddSmile/";

                $this->assign( 'smile_list',$smilelist );
                $this->assign( 'action_path',$path );
                $this->assign( 'smilepath',__PUBLIC__.'/images/biaoqing/'.$type.'/' );
                $this->assign( 'smiletype',$type );
                $this->display(  );
        }


        /**
         * doEditSmile
         * 编辑表情
         * @access public
         * @return void
         */
        public function doEditSmile( ) {
                $smilDao = D('Smile');
                if( count( array_filter( $_POST['emotion'] ) ) < count( $_POST['emotion'] ) ) {
                        $this->error( "修改失败，不允许表情缩写为空" );
                        exit;
                }

                if( count( array_filter( $_POST['title'] ) ) < count( $_POST['title'] ) ) {
                        $this->error( "修改失败，不允许表情标题为空" );
                        exit;
                }
                if( $smilDao->editSmile( $_POST['emotion'],$_POST['title'],$_POST['type'] ) ) {
                        $this->redirect( '/System/smile/type/'.$_POST['type'] );
                }else {
                        $this->error( "修改失败" );
                }
        }

        /**
         * doAddSmile
         * 添加表情
         * @access public
         * @return void
         */
        public function doAddSmile() {
                $smilDao = D('Smile');
                $result = $smilDao->addSmile( $_POST,true );
                if( count( array_filter($_POST) ) < count( $_POST ) )
                        $this->error( "添加失败，轻完整填写" );
                if(true == $result) {
                        $this->redirect( '/System/smile/type/'.$_POST['type'] );
                }elseif( 'has_file' == $reuslt ) {
                        $this->error( "添加失败，和现有文件名重名。" );
                }else {
                        $this->error( "添加失败，请检查文件是否存在于{$_POST['type']}文件夹下" );

                }
        }


        public function doDeleteSmileType() {
                if( !isset( $_POST['type'] ) && empty( $_POST['type'] ) ) {
                        echo -1;
                        exit();
                }
                $type = $_POST['type'];
                $map['type'] = array( 'in',"'{$type}'");
                if( D('Smile')->where( $map )->delete() ) {
                        if( !strpos( $_POST['type'],',' ) ) {
                                echo 1;
                        }else {
                                echo 2;
                        }
                }else {
                        echo -1;
                }
        }


       /**
         * doChangeIco
         * 删除表情
         * @access public
         * @return void
         */
        public function doDeleteSmile(){
            $id     = $_POST['id'];
            $type   = $_POST['type'];
            $idlist = explode( ',',$id );
            $smile = D( 'Smile' );

            if( $smile->deleteSmile( $idlist,$type ) ){
                echo -1;
                exit();
            }
            if( !strpos( $_POST['id'],',' ) ){
                    echo 1;
            }else{
                echo 2;
            }
        }


	/**
	 * attach
	 * 附件管理
	 * @access public
	 * @return void
	 */
	public function attach() {
		//For 分页
		$post  = array();
		if($_POST) {
			$post = $_POST;
			Session::set('attach_search',serialize($_POST));
		}else if(isset($_GET['p'])) {
			if(Session::get('attach_search')) {
				$post = unserialize(Session::get('attach_search'));
			}
		}else {
			unset($_SESSION['attach_search']);
		}

		$model = D('Attach');
		$this->assign('attach_types', $model->getAttachType());
		$this->assign('extensions',	  $model->getExtensionType());
		$this->assign($model->getAttachList($post));
		$this->assign($post);

		//附件的限制条件
		unset($model);
		$model = model('Xdata');
		$res   = $model->lget('site');
		$this->assign($res);
		
		$this->display();
	}

	//设置附件的限制条件（size & type）
	public function doAttachLimit() {
		$model = model('Xdata');
		$res   = $model->lput('site', $_POST);
		if($res) {
			addLog($this->mid, '', 'attach_set');
			
			$this->success('保存成功～');
		}else {
			$this->error('保存失败～');
		}
	}

	//下载附件
	public function downloadAttach() {
		$model  = M('x_attach');
		$attach = $model->where('id='.intval($_GET['id']))->limit(1)->findAll();
		if(!$attach) {
			$this->error('附件不存在～');
		}
		$attach = $attach[0];

		//下载函数
		import("ORG.Net.Http"); 

		$filePath = UPLOAD_PATH . '/' . $attach['savepath'] . '/' . $attach['savename'];
		if(file_exists($filePath)) {
			//增加下载次数
			$model->setInc('totaldowns', 'id=' . intval($_GET['id']));

			$name = iconv("utf-8",'gb2312',$attach['name']);
			Http::download($filePath,$name);
		}else {
			$this->error('附件不存在～');
		}
	}

	//删除附件至回收站
	public function doDeleteAttach() {
		$model = M('x_attach');
		$ids = is_array($_POST['id']) ? $_POST['id'] : array(intval($_POST['id']));
		foreach ($ids as $v) {
			$model->where('id='.$v)->setField('del', 1);
		}
		
		$num = count($ids);
		addLog($this->mid, array('num'=>$num), 'attach_delete');
		
		echo 1;
	}

	//还原附件
	public function doRevertAttach() {
		$model = M('x_attach');
		$res = true;
		$ids = is_array($_POST['id']) ? $_POST['id'] : array(intval($_POST['id']));
		foreach ($ids as $v) {
			$model->where('id='.$v)->setField('del', 0);
		}
		echo 1;
	}

	//附件回收站
	public function attach_recycle() {
		$res = M('x_attach')->where('del=1')->order('mtime DESC')->findPage(20);
		$this->assign($res);
		$this->display();
	}
	
	/**
	 * feed
	 * 动态管理
	 * @access public
	 * @return void
	 */
	public function feed() {
		//For 分页
		$post  = array();
		if($_POST) {
			$post = $_POST;
			Session::set('attach_search',serialize($_POST));
		}else if(isset($_GET['p'])) {
			if(Session::get('attach_search')) {
				$post = unserialize(Session::get('attach_search'));
			}
		}else {
			unset($_SESSION['attach_search']);
		}
		$this->assign($post);

		//根据POST，组装查询条件
		$limit = '20';
		$field = 'id,uid,type,title,cTime,appname';
		$map   = array();
		if(!empty($post['userId'])) {
			$map['uid'] = array('in', $post['userId']);
		}
		if(!empty($post['type'])) {
			$map['type'] = $post['type'];
		}
		if(!empty($post['appname'])) {
			$map['appname'] = $post['appname'];
		}
		if(!empty($post['limit'])) {
			$limit = intval($post['limit']);
		}
		if(!empty($post['limit'])) {
			$limit = intval($post['limit']);
		}

		//获取所有type和appname
		$model    = M('feed');
		$appnames = formatArray( $model->field('appname')->Distinct(true)->findAll(), 'appname' );
		$types    = formatArray( $model->field('type')->Distinct(true)->findAll(), 'type' );
		$this->assign('appnames', $appnames);
		$this->assign('types', $types);

		$service = service('Feed');
		$res = $service->get($map, $limit,false,0,false,false);//dump($res);exit;
		$this->assign($res);

		$this->display();
	}
	
	function upFeedCache(){
		if( M('')->execute("UPDATE ".C('DB_PREFIX')."feed SET `cache_cn`='',`cache_en`=''")){
			$this->success('操作成功');
		}else{
			$this->error('操作失败');
		}
		
	}

	//删除动态
	public function doDeleteFeed() {
		$model = M('feed');
		$ids = is_array($_POST['id']) ? $_POST['id'] : array(intval($_POST['id']));
		$map['id'] = array('in', $ids);
		$model->where($map)->delete();
		
		$num = count($ids);
		addLog($this->mid, array('num'=>$num), 'feed_delete');
		
		echo 1;
	}

	/**
	 * domain
	 * 认证设置
	 * @access public
	 * @return void
	 */
	public function domain() {
		$model  = model('Xdata');
		$domain = $model->lget('domain');
		$this->assign($domain);
		$this->display();
	}

	//设置域信息和公共帐号
	public function doSaveDomain() {
		$model = model('Xdata');
		$res   = $model->lput('domain', $_POST);
		if($res) {
			addLog($this->mid, '', 'domain_edit');
			
			$this->success('保存成功～');
		}else {
			$this->error('保存失败～');
		}
	}

	/**
	 * email
	 * 系统邮件设置
	 * @access public
	 * @return void
	 */
	public function email() {
		$model  = model('Xdata');
		$email = $model->lget('email');
		$this->assign($email);
		$this->display();
	}
	
	//保存邮件设置
	public function doSaveEmail() {
		$model = model('Xdata');
		$res   = $model->lput('email', $_POST);
		if($res) {
			addLog($this->mid, '', 'mail_set');
			
			$this->success('保存成功～');
		}else {
			$this->error('保存失败～');
		}
	}

	//发送测试邮件
	public function doSendEmail() {
		$service = service('Mail');
		$subject = '这是一封测试邮件';
		$content = '这是一封测试邮件，您能收到这封邮件表明邮件服务器已配置正确。<br />
					如果您不清楚这封邮件的来由，请删除，为给您带来的不便表示歉意';
		$service->send_email($_POST['receiver'], $subject, $content);
		echo 1;
	}

	/**
	 * scores
	 * 积分规则
	 * @access public
	 * @return void
	 */
	public function scores() {
		$model = M('x_data');
		$map['`list`'] = 'user_credit';
		$res = $model->where($map)->order('id ASC')->findAll();
		$list  = array();
		foreach($res as $v) {
			$v['value'] = unserialize($v['value']);
			$list[$v['id']] = $v;
		}
		$this->assign('list', $list);
		$this->display();
	}

	//添加新的积分规则
	public function doAddScore() {
		$data = $this->_checkScore($_POST);
		$res = M('x_data')->add($data);
		if($res) {
			$this->success('保存成功～');
		}else {
			$this->error('保存失败～');
		}
	}

	//编辑一条积分规则
	public function doSaveOneScore() {
		$model = M('x_data');
		//合法性检查
		if( (!is_numeric($_POST['score']) && $_POST['score'] != '$') || (!is_numeric($_POST['exp']) && $_POST['score'] != '$') ) {
			echo 0;return;
		}

		//保存入库
		$value = array(
			'action' => t($_POST['action']),
			'score'  => $_POST['score'],
			'exp'	 => $_POST['exp'],
			'title'  => t($_POST['title']),
			'info'   => t($_POST['info'])
		);
		$data['list'] = 'user_credit';
		$data['key']  = t($_POST['action']);
		$data['value']= serialize($value);
		$res = $model->where('id='.intval($_POST['id']))->save($data);
		if($res) {
			echo 1;
		}else {
			echo 0;
		}
	}

	//保存所有的积分设置
	public function doSaveAllScore() {
		$model = M('x_data');

		//获取所有的积分配置的ID
		$map['`list`'] = 'user_credit';
		$ids = $model->where($map)->field('id')->findAll();
		$ids = formatArray($ids, 'id');
		
		//组装所有新的积分配置，并保存入库
		foreach($ids as $k => $v) {
			$score['action'] = $_POST['action'][$v];
			$score['score']  = $_POST['score'][$v];
			$score['exp']    = $_POST['exp'][$v];
			$score['title']  = $_POST['title'][$v];
			$score['info']   = $_POST['info'][$v];
			$data = $this->_checkScore($score, $v);
			$res = $model->where('id='.intval($v))->save($data);
			unset($score);
			unset($res);
		}
		
		addLog($this->mid, '', 'score_edit');
		
		$this->success('保存成功～');
	}

	//删除积分规则
	public function doDeleteScore() {
		$model = M('x_data');
		$ids = is_array($_POST['id']) ? $_POST['id'] : array(intval($_POST['id']));
		$map['id'] = array('in', $ids);
		$model->where($map)->delete();
		echo 1;
	}

	//检测动作名是否可用
	public function isValidAction() {
		if( empty($_POST['action']) ) {
			echo 0;
		}else {
			$map['`list`'] = 'user_credit';
			$map['`key`']  = t($_POST['action']);
			$res = M('x_data')->where($map)->limit(1)->findAll();
			if($res) {
				echo 0;
			}else {
				echo 1;
			}
		}
	}

	protected function _checkScore($post, $id = 0) {
		$model = M('x_data');
		//合法性检查
		$map['`list`'] = 'user_credit';
		$map['`key`']  = t($post['action']);
		if($id != 0) {
			$map['id'] = array('neq', $id);
		}
		$res = $model->where($map)->limit(1)->findAll();
		if($res) {
			$error = ($id == 0) ? '动作名已存在～' : 'ID = ' . $id . '的动作名已存在～';
			$this->error($error);
		}
		if( (!is_numeric($post['score']) && $post['score'] != '$') || (!is_numeric($post['exp']) && $post['score'] != '$') ) {
			$error = ($id == 0) ? '金币数/贡献值必须为数字或$～' : 'ID = ' . $id . '的金币数/贡献值必须为数字或$～';
			$this->error($error);
		}

		//保存入库
		$value = array(
			'action' => t($post['action']),
			'score'  => $post['score'],
			'exp'	 => $post['exp'],
			'title'  => t($post['title']),
			'info'   => t($post['info'])
		);
		$data['list'] = 'user_credit';
		$data['key']  = t($post['action']);
		$data['value']= serialize($value);
		return $data;
	}

	/**
	 * schedule
	 * 计划任务管理
	 * @access public
	 * @return void
	 */
	public function schedule() {
		$dao  = service('Schedule');
		$list = $dao->getScheduleList();
		foreach($list as $k => $v) {
			$task = unserialize($v['task_to_run']);
			$list[$k]['task_to_run'] = $task;
			unset($task['type']);
			$list[$k]['method'] = implode('/',$task);
		}
		$this->assign('list', $list);
		$this->display();
	}

	//新建计划任务
	public function doAddSchedule() {
		$data = $this->_formatSchedule($_POST);
		$res  = service('Schedule')->addSchedule($data);

		if($res) {
			$this->success('保存成功～');
		}else {
			$this->error('保存失败～');
		}
	}

	//保存一条计划任务
	public function doSaveOneSchedule() {
		$data = $this->_formatSchedule($_POST);
		$res  = service('Schedule')->saveSchedule($data);
		if($res) {
			echo 1;
		}else {
			echo 0;
		}
	}

	//保存所有计划任务
	public function doSaveAllSchedule() {
		//获取所有计划任务的IDs
		$ids = M('schedule')->field('id')->findAll();
		$ids = formatArray($ids, 'id');
		
		//组装所有新的积分配置，并保存入库
		$service = service('Schedule');
		foreach($ids as $k => $v) {
			$post['id']				= $v;
			$post['task_to_run']	= $_POST['task_to_run'][$v];
			$post['info']			= $_POST['info'][$v];
			$post['schedule_type']  = $_POST['schedule_type'][$v];
			$post['modifier']		= $_POST['modifier'][$v];
			$post['dirlist']		= $_POST['dirlist'][$v];
			$post['month']			= $_POST['month'][$v];
			$post['start_datetime'] = $_POST['start_datetime'][$v];
			$post['end_datetime']   = $_POST['end_datetime'][$v];
			$post['last_run_time']  = $_POST['last_run_time'][$v];

			$data = $this->_formatSchedule($post);
			if( !$service->isValidSchedule($data) ) {
				$this->error('ID = ' . $v . '参数有错误，请检查～');
			}
			$service->saveSchedule($data);

			unset($post);
			unset($data);
		}
		
		addLog($this->mid, '', 'plan_edit');
		
		$this->success('保存成功～');
	}

	//删除计划任务
	public function doDeleteSchedule() {
		$model = M('schedule');
		$ids = is_array($_POST['id']) ? $_POST['id'] : array(intval($_POST['id']));
		$map['id'] = array('in', $ids);
		$model->where($map)->delete();
		
		$num = count($ids);
		addLog($this->mid, array('num'=>$num), 'plan_del');
		
		echo 1;
	}

	//格式化计划任务的数据
	protected function _formatSchedule($post) {
		foreach($post as $k => $v) {
			if(empty($v)) $post[$k] = NULL;
		}

		$task = explode('/', $post['task_to_run']);
		$post['task_to_run'] = array(
			'type'   => 'model',
			'app'    => $task[0],
			'model'  => $task[1],
			'method' => $task[2]
		);
		$post['task_to_run'] = serialize($post['task_to_run']);
		unset($post['__hash__']);
		return $post;
	}

	/*
	 * vote
	 * 投票
	 * @access pulbic
	 * @return void
	 */
	public function vote() {
		//For分页
		$post  = array();
		if($_POST) {
			$post = $_POST;
			Session::set('vote_search',serialize($_POST));
		}else if(isset($_GET['p'])) {
			if(Session::get('vote_search')) {
				$post = unserialize(Session::get('vote_search'));
			}
		}else {
			unset($_SESSION['vote_search']);
		}
		$this->assign($post);

		$model = D('Vote');
		$this->assign($model->getVoteList($post));
		$this->display();
	}

	//删除投票
	public function doDeleteVote() {
		$v_model = M('vote');
		$o_model = M('vote_opt');
		$u_model = M('vote_user');
		$ids = is_array($_POST['id']) ? $_POST['id'] : array(intval($_POST['id']));
		foreach ($ids as $k=>$v) {
			$v_model->where('id='.$v)->delete();
			$o_model->where('vote_id='.$v)->delete();
			$u_model->where('vote_id='.$v)->delete();
		}		
		
		addLog($this->mid, array('num'=>$k+1), 'vote_delete');
		
		echo 1;
	}

	/**
	 * 安全测试
	 * @access public
	 * @return void
	 */
	public function security() {
		//For分页
		$post  = array();
		if($_POST) {
			$post = $_POST;
			Session::set('s_search',serialize($_POST));
		}else if(isset($_GET['p'])) {
			if(Session::get('s_search')) {
				$post = unserialize(Session::get('s_search'));
			}
		}else {
			unset($_SESSION['s_search']);
		}
		$this->assign($post);

		$data = D('Security', 'admin')->getList($post);

		$this->assign($data);
		$this->display();
	}

	public function securityExcel() {
		D('Security','admin')->outExcel();
	}

	public function doIgnoreSecurity() {
	}

	//生成密码
	public function makePassword() {
		if($_POST['old']){
			include SITE_PATH.'/addons/libs/3des.php';
			$crypt	=	new Crypt3DES;
			$encode	=	$crypt->encrypt($_POST['old']);
			//echo $encode.'<br />';
			$this->assign('oldpassword',$_POST['old']);
			$this->assign('newpassword',$encode);
			//$decode	=	$crypt->decrypt($encode);
			//echo $decode.'<br />';
		}
		$this->display();
	}
}
?>
